/*
 * 
 */

YUI.add('projectliview', function (Y) {
	
	Y.namespace('AppView');
	Y.AppView.ProjectLiView = Y.Base.create('projectLiView', Y.View, [], {
	    // 由于相同结构的嵌套，无法通过class selector获取当前li包含的对象，只能通过id来甄别。
	    events: {},
	    attachEvents: function (events) {
	        var container = this.get('container'),
	        	mid = this.get('model').get('id'),
	        	dp = this.get('model').get('dp'),
	        	ke = (Y.UA.webkit || Y.UA.ie) ? 'keydown' : 'keypress';
	        container.delegate(ke, this.projectTextareaKeyPressed, '#project-textarea--'  + mid, this);
	        container.delegate('blur', this.projectBlur, '#project-textarea--'  + mid, this);
	        container.delegate(ke, this.noteTextareaKeyPressed, '#note-textarea--'  + mid, this);
	        container.delegate('blur', this.noteBlur, '#note-textarea--'  + mid, this);
	        container.delegate('mouseover', this.hoverOn, '#project-tr--'  + mid, this);
	        container.delegate('mouseout', this.hoverOff, '#project-tr--'  + mid, this);
	        container.delegate(['click'], this.editProject, '#project-content--'  + mid +',#project-td--'  + mid, this);
	        container.delegate(['click'], this.showItemMenu, '#bullet-td--'  + mid, this);
	        container.delegate(['click'], this.editNote, '#note-content--'  + mid +',#note-td--'  + mid, this);
	        container.delegate(['click'], this.closeOpen, '#close-open-a--'  + mid, this);
	        //copy from yui view
	        var  owns = Y.Object.owns,
	            handler, handlers, name, selector;
	        for (selector in events) {
	            if (!owns(events, selector)) { continue; }
	            handlers = events[selector];
	            for (name in handlers) {
	                if (!owns(handlers, name)) { continue; }
	                handler = handlers[name];
	                if (typeof handler === 'string') {
	                    handler = this[handler];
	                }
	                container.delegate(name, handler, selector, this);
	            }
	        }
	    },

	    // The template property holds the contents of the #project-item-template
	    // element, which will be used as the HTML template for each project item.
	    template: Y.one('#project-item-template').getContent(),
	    
	    initializer: function () {
	        var model = this.get('model');
	        // Re-render this view when the model changes, and destroy this view
	        // when the model is destroyed.
	        model.after('change', this.change, this);
	        model.after('destroy', this.destroy, this);
	        this.set('hasRender',false);
	    },
	    
	    change:function(e){
	    	var changed = e.changed;
	    	if(Y.Object.isEmpty(changed)){
	    		return;
	    	}
	    	changed['mid'] = this.get('model').get('id');
	    	changed['action'] = 'modify';
	    	changed['uid'] = this.get('model').get('uid');
	    	Y.changeHistory.add(changed);
	    	var domnode = this.get('container').getDOMNode(); 
	    	if(changed['open']){
        		if(changed['open'].newVal){
        			if(domnode){
        				this.get('container').removeClass('closed');
        				this.get('bulletTd').removeClass('has-children-closed');
        			}
        		}else{
        			if(domnode){
        				this.get('container').addClass('closed');
        				this.get('bulletTd').addClass('has-children-closed');
        			}
        		}
	    	}
	    	if(changed['title']){
		    		var tnv = changed['title'].newVal;
		    		if(this.get('editing')){
		    			this.get('projectContent').setContent(Y.Escape.html(tnv));
		    		}else{
		    			this.get('projectContent').setContent(Y.Wfwrapper(tnv));
		    			this.get('projectTextarea').set('value',tnv);
		    		}
		    		
	    	}
	    	
	    	if(changed['note']){
	    		if(this.get('editing')){
	    			this.get('noteContent').setContent(Y.Escape.html(nnv));
	    		}else{
		    		var nnv = changed['note'].newVal;
		    		this.get('noteTextarea').set('value',nnv);
		    		if(!nnv){
		    			this.get('table').addClass('emptynote');
		    		}else{
		    			this.get('table').removeClass('emptynote');
		    		}
	    		}
	    	}
	    	
	    	if(changed['dp']){
	    		this.destroy();
	    	}
	    	
	    	if(changed['position']){
	    		this.destroy();
	    	}
	    	
	    	if(changed['shareType']){
	    		if('none' == changed['shareType'].newVal){
	    			this.get('bulletTd').removeClass('shared');
	    		}else{
	    			this.get('bulletTd').addClass('shared');
	    		}
	    	}
	    	
	    	if(changed['path']){
	    		var p = changed['path'];
	    		changed['touchedpath'] = p.prevVal + ',' + p.newVal;
	    	}else{
	    		changed['touchedpath'] = this.get('model').get('path');
	    	}
	    },
	    
	    render: function () {
	    	if(!this.get('hasRender')){
	    		this.set('hasRender',true);
	            var container = this.get('container'),
	            model     = this.get('model'),
	            dn      = model.get('done'),
	            mid = model.get('id'),
	            dp = model.get('dp'),
	            title = model.get('title');
	            note = model.get('note');
//	            Y.log('title:' + title);
		        container.set('id', 'li--'  + mid);
		        container.setContent(Y.Lang.sub(this.template, {
		            checked: dn ? 'checked' : '',
		            escape_title   : Y.Wfwrapper(title),
		            title :title,
		            note :note,
		            escape_note:Y.Escape.html(note),
		            projectId : mid,
		            dp : dp
		        }));
		        container[dn ? 'addClass' : 'removeClass']('project-done');
		        var mid = model.get('id');
		        this.set('editing',false);
		        this.set('table',container.one('#table--'  + mid));
		        this.set('projectTextarea', container.one('#project-textarea--'  + mid));
		        this.set('projectContent', container.one('#project-content--'  + mid));
		        this.set('noteContent', container.one('#note-content--'  + mid));
		        this.set('noteTextarea', container.one('#note-textarea--'  + mid));
		        this.set('projectTd', container.one('#project-td--'  + mid));
		        this.set('noteTd', container.one('#note-td--'  + mid));
		        this.set('noteTr',container.one('#note-tr--'  + mid));
		        this.set('closeOpenTd',container.one('#close-open-td--'  + mid));
		        this.set('closeOpenA',container.one('#close-open-a--'  + mid));
		        this.set('projectTr',container.one('#project-tr--'  + mid));
		        this.set('bulletTd',container.one('#bullet-td--'  + mid));
		        this.get('projectTextarea').on('valueChange',this.contentValueChange,this);
		        this.get('noteTextarea').on('valueChange',this.contentValueChange,this);
		        
		        var ulv = new Y.AppView.ProjectUlView({parentId:model.get('id')});
		        if(model.get('open')){
		        	this.get('container').removeClass('closed');
		        }else{
		        	this.get('container').addClass('closed');
		        }
		        
		        if('public' == model.get('shareType') || 'public-editable' == model.get('shareType')){
		        	this.get('bulletTd').addClass('shared');
		        }
		        
		        if(!model.get('note')){
		        	this.get('table').addClass('emptynote');
		        }
		        container.append(ulv.get('container'));
		        if(ulv.get('container').getContent() && !model.get('open')){
		        	this.get('bulletTd').addClass('has-children-closed');
		        }
	    	}
	        return this;
	    },
	    // Toggles this item into edit mode.
	    editProject: function (e) {
	    	if(Y.readOnly)return;
	    	this.set('editing',true);
	    	if(Y.filterMode){
	    		var history = new Y.HistoryHash();
	    		var mid = this.get('model').get('id');
	    		history.add({q:null,item:mid});
	    	}else{
	    		Y.Wfutils.focusEditingProject(this.get('container'),"origin");
	    	}
	    },
	    
	    showItemMenu:function(e){
	    	e.preventDefault();
	    	if(Y.readOnly){
	    		Y.showMsg('只读模式，不支持操作菜单！',1500);
	    		return;
	    	}
	    	Y.itemMenu.show();
	    	Y.all('.bullet-clicked').removeClass('bullet-clicked');
	    	this.get('bulletTd').addClass('bullet-clicked');
	    	Y.lastClickedItemId = this.get('model').get('id');
	    	Y.itemMenu.setXY([e.pageX + 10,e.pageY - 35]);
	    },
	    
	    editNote: function (e) {
	    	if(Y.readOnley)return;
			Y.Wfutils.focusEditingNote(this.get('container'),"origin");
	    },
	    
	    // When the enter key is pressed, focus the new project input field. This
	    // causes a blur event on the current edit field, which calls the save()
	    // handler below.
	    projectTextareaKeyPressed: function (e) {
	    		var keyCode = e.keyCode;
	    		var model = this.get('model');
	    		var container = this.get('container');
	    		Y.log(keyCode);
		    	switch (keyCode) {
		    	case 79://o
		    		if(e.ctrlKey){
		    			e.preventDefault();
		    			this.get('model').set('open',!this.get('model').get('open')).save();
		    		}
		    		break;
				case 13:
					e.preventDefault();
					if(e.ctrlKey){
						Y.Wfutils.focusEditingNote(model, "end");
					}else{
						if(model.hasChildren() && model.get('open')){
							var clist  = Y.projectListList[model.get('id')];
							var preOrder = clist.prevPosition(clist.firstModel());
							clist.create({dp:model.get('id'),path:model.get('path') + ',' + model.get('id'),position:preOrder,shareType:model.get('shareType')});
						}else{
							var dp = model.get('dp');
							var list  = Y.projectListList[dp];
							var nextOrder = list.nextPosition(model);
							var st = Y.totalDataHash[dp];
							if(st){
								st = st.getValue('shareType');
							}else{
								st = 'none';
							}
							
							list.create({dp:dp,path:model.get('path'),position:nextOrder,shareType:st});
						}
					}
					break;
				case 40:
					e.preventDefault();
					this.moveToNextOrDown();
					break;
				case 39:
					if(Y.Wfutils.cursorAtLast(this.get('projectTextarea'))){
						e.preventDefault();
						Y.Wfutils.focusEditingNote(container, "start");
					}
					break;
				case 38:
					if(e.shiftKey){
						;
					}else{
						e.preventDefault();
						this.moveToPreOrUp(false);
					}
					break;
				case 37:
					if(Y.Wfutils.cursorAtStart(this.get('projectTextarea'))){
						e.preventDefault();
						this.moveToPreOrUp(false);
					}
					break;
				case 8:
			    	var tv = this.get('projectTextarea').get('value');
			    	if(!tv || Y.Lang.trim(tv).length == 0){
			    		e.preventDefault();
			    		if(!this.get('model').canDelete()){
			    			Y.showMsg('您没有删除该节点的权限！',2000);
			    			return;
			    		}
			    		this.moveToPreOrUp(true);
			    		this.get('model').destroy({'delete':true});
			    	}
		        	break;
				case 9:
					e.preventDefault();
					var textvalue = this.get('projectTextarea').get('value');
					if(e.shiftKey){
						if(model.hasParent()){//如果有父目录，就成为父目录的下方兄弟
							var parentModel = model.getParent();
							var list = Y.projectListList[model.get('dp')];
							var parentList = Y.projectListList[parentModel.get('dp')];
							var nextModel = list.next(parentModel);
							if(nextModel){//有下方兄弟，就加到它的前面。
								model.setAttrs({'dp':parentModel.get('dp'),path:parentModel.get('path'),position:parentList.prevPosition(nextModel),'title':textvalue}).save();
							}else{//没有下方兄弟，就成为父目录的儿子
								model.setAttrs({'dp':parentModel.get('dp'),path:parentModel.get('path'),position:parentList.nextPosition(parentModel),'title':textvalue}).save();
							}
							this.constructor.superclass.remove.call(this);
							parentList.add(this.get('model'));
							list.remove(this.get('model'));
							this.destroy();
						}
					}else{
						var list = Y.projectListList[model.get('dp')];
						var prevModel = list.previous(model);
						if(prevModel){
							prevModel.set('open',true).save();
							var preList = Y.projectListList[prevModel.get('id')];
							var lastModel = preList.lastModel(prevModel);
							
							var path = prevModel.get('path');
							if(!path){
								path = prevModel.get('id');
							}else{
								path = prevModel.get('path') + "," + prevModel.get('id');
							}
							model.setAttrs({'path': path,'dp':prevModel.get('id'),position:preList.nextPosition(lastModel),'title':textvalue}).save();
							this.constructor.superclass.remove.call(this);
							preList.add(this.get('model'));
							list.remove(this.get('model'));
						}
					}
					break;
				default:
				}
	    },
	    
	    noteTextareaKeyPressed: function (e) {
			var keyCode = e.keyCode;
			var mid = this.get('model').get('id');
	    	switch (keyCode) {
			case 40:
			case 39:
				if(Y.Wfutils.cursorAtLast(this.get('noteTextarea'))){
					e.preventDefault();
					this.moveToNextOrDown();
				}
				break;
			case 38:
				if(Y.Wfutils.cursorAtStart(this.get('noteTextarea'))){
					e.preventDefault();
					Y.Wfutils.focusEditingProject(this.get('container'), "end");
				}
				break;
			case 37:
				if(Y.Wfutils.cursorAtStart(this.get('noteTextarea'))){
					e.preventDefault();
					Y.Wfutils.focusEditingProject(this.get('container'), "end");
				}
				break;
			case 9:
				e.preventDefault();
				break;
			case 8:
		    	var tv = this.get('noteTextarea').get('value');
		    	if(!tv || tv.length == 0){
		    		e.preventDefault();
		    		Y.Wfutils.focusEditingProject(this.get('container'),"end");
		    	}
	        	break;
			default:
			}
	    },
	    
	    moveToPreOrUp:function(){
	    	var model = this.get('model');
	    	var list = Y.projectListList[model.get('dp')];
	    	var preModel = list.previous(model);
	    	var moved = false;
	    	if(preModel){
	    		var plmodels = preModel.getLastDeepestOpenChild();
	    		if(plmodels.length > 0){
	    			var plmodel = plmodels.slice(-1)[0];
            		Y.Wfutils.focusEditingProject(plmodel,"end");
            		moved = true;
	    		}
	    		if(!moved){
	    			Y.Wfutils.focusEditingProject(preModel,"end");
	    			moved = true;
	    		}
	    	}
	    	if(!moved){
		    	var parentModel = model.getParent();
		    	if(parentModel){
		    		Y.Wfutils.focusEditingProject(parentModel,"end");
		    	}
	    	}
	    },
	    
	    moveToNextOrDown:function(){
	    	//如果自己有儿子，并且自己没有隐藏的话，就进入。
	    	var model = this.get('model');
	    	var list = Y.projectListList[model.get('dp')];
	    	var moved = false;
	    	if(model.hasChildren()){
	    		if(model.get('open')){
	    			var clist = Y.projectListList[model.get('id')];
	    			var firstModel = clist.firstModel();
	    			if(firstModel){
	    				Y.Wfutils.focusEditingProject(firstModel,"end");
	    				moved = true;
	    			}
	    		}
	    	}
	    	
	    	if(!moved){//如果有下方兄弟
	    		var nextModel = list.next(model);
	    		if(nextModel){
	    			Y.Wfutils.focusEditingProject(nextModel,"end");
	    			moved = true;
	    		}
	    	}
	    	
	    	if(!moved){
	    		var parents = model.getParents();
	    		Y.some(parents,function(parent){
	    			var plist = Y.projectListList[parent.get('dp')];
	    			var pnextModel = plist.next(parent);
	    			if(pnextModel){
	    				Y.Wfutils.focusEditingProject(pnextModel,"end");
	    				return true;
	    			}
	    		});
	    	}
	    },
	    noteBlur:function(e){
	    	var nt = this.get('noteTextarea').get('value');
//	    	this.get('model').set('note',Y.Lang.trim(nt)).save();
	    	this.get('model').set('note',nt).save();
	    	this.get('noteContent').setContent(nt);
			this.get('noteTd').removeClass('editing');
			if(!this.get('model').get('note')){
				this.get('table').addClass('emptynote');
			}
	    },
	    
	    projectBlur:function(e){
	    	var pt = this.get('projectTextarea').get('value');
	    	this.set('editing',false);
	    	var trimedPt = Y.Lang.trim(pt);
	    	if(pt != trimedPt){
	    		this.get('model').set('title',trimedPt).save();
	    	}
	    	this.get('projectContent').setContent(Y.Wfwrapper(pt));
			this.get('projectTd').removeClass('editing');
	    },
	    
//	    entryProject :function(e){
//	    	var history = new Y.HistoryHash();
//	    	history.addValue('item',this.get('model').get('id'));
//	    },
	    
	    contentValueChange: function(e){
//	    	this.set('vctimes',this.get('vctimes') + 1);
	    	var sh = e.target.get('scrollHeight'); 
	    	this.set('editing',true);
	    	e.target.setStyle('height',sh + 'px');
//	    	if(this.get('vctimes') > 10){
//	    		this.set('vctimes',0);
	    		this.get('model').setAttrs({'title':this.get('projectTextarea').get('value'),
	    									'note':this.get('noteTextarea').get('value')});
//	    	}
	    },
	    
	    saveNote: function () {
	        this.get('noteTd').removeClass('editing');
	        this.get('model').set('note', this.get('noteTextarea').get('value')).save();
	    },
	    
	    hoverOn:function(e){
	    	var c = this.get('closeOpenA');
			if(!this.get('container').one('ul li')){
				c.setContent("");
			}else{
				if(this.get('model').get('open')){
					c.setContent('-');
				}else{
					c.setContent('+');
				}
			}
			this.get('projectTr').addClass('project-tr-hover-on');
	    },
	    closeOpen:function(e){
	    	e.preventDefault();
	    	var m = this.get('model');
	    	m.set('open',!m.get('open')).save();
	    },
	    hoverOff:function(e){
			this.get('projectTr').removeClass('project-tr-hover-on');
	   	}
	}, {
	    ATTRS: {
	        container: {
	            valueFn: function () {
	                return Y.Node.create('<li class="project-item"/>');
	            }
	        }
	    }
	});
},'0.0.1',{requires:['node','base','event-synthetic','event','view','model', 'model-list','escape']});